import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
import java.io.*;

public class SpreadSheet extends MIDlet implements CommandListener,ItemStateListener
{
    private static final Command CMD_EXIT = new Command("Exit", Command.EXIT, 1);
    private Display display;
    private boolean firstTime;
    private Form mainForm;
	private SpreadSheetCanvas canvas;
	private Table table;
	private RecordsForm recordsForm;
    
	public SpreadSheet() 
	{
        firstTime = true;
        mainForm = new Form("SpreadSheet");
		canvas = new SpreadSheetCanvas();	
		table = new Table("", Display.getDisplay(this),this,canvas.width,canvas.height);
		recordsForm = new RecordsForm(table,display);
    }

    protected void startApp() 
	{
        if (firstTime) 
		{
			try
			{
				display = Display.getDisplay(this);
				display.setCurrent(canvas);
				Thread.sleep(3000);
				mainForm.append(table);
      			mainForm.addCommand(CMD_EXIT);
				mainForm.setCommandListener(this);
				mainForm.setItemStateListener(this);
				firstTime = false;
			}
			catch(InterruptedException exc)
			{
			}
        }

		recordsForm.display = display;
		if(recordsForm.records > 0)
		{
			display.setCurrent(recordsForm.recordsList);
		}
		else
		{
			display.setCurrentItem(table);
		}        
    }

    public void commandAction(Command c, Displayable d) 
	{
        if (c == CMD_EXIT) 
		{
            destroyApp(false);
            notifyDestroyed();
        }
    }

	public void itemStateChanged(Item item)
	{
	}

    protected void destroyApp(boolean unconditional) 
	{
    }

	protected void pauseApp() 
	{
	}
}

class SpreadSheetCanvas extends Canvas
{

	public int height=0; 
	public int width =0;

	public SpreadSheetCanvas()
	{
		height = getHeight();
		width = getWidth();
	}
	
	public void paint(Graphics g)
	{
		try
		{
			g.setColor(255,255,255);
			g.fillRect(0,0,1000,1000);
			Class spreadSheet = Class.forName("SpreadSheet");
			InputStream s = spreadSheet.getResourceAsStream("/SimpleSpreadsheet.png");
			Image image = Image.createImage(s);
			g.drawImage(image,(width-124)/2,(height-43)/2,Graphics.LEFT | Graphics.TOP);
		}
		catch(IOException exc)
		{
		}
		catch(ClassNotFoundException exc)
		{
		}
	}
}
